<template>
  <div>
    <Nav/>
    <div class="content">
          <nav aria-label="breadcrumb" style="display: inline-block;">
              <ol class="breadcrumb">
                  <li class="breadcrumb-item" v-for="(item, index) in dirPathList" @click="index == dirPathList.length - 1 ? '' : changeDir(index)">
                      <a href="javascript:;" v-bind:class="index == dirPathList.length - 1 ? 'disabled-link' : ''">{{ item }}</a>
                  </li>
              </ol>
          </nav>
          <select @change="changeFileType" v-model='queryParam.type' class="form-select" aria-label="Default select example" style="display: inline-block; width: 130px; margin-left: 100px;">
              <option value="ALL">所有文件</option>
              <option value="IMAGE">图像</option>
              <option value="DIR">目录</option>
          </select>

          <span>
              <button v-bind:class="anyFileSelected ? '' : 'disabled'" type="button" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#delete-file-modal">
                  删除
              </button>
              <ConfirmDialog id="delete-file-modal" title="提醒" v-bind:msg="'确定删除文件：' + selectedFileDescription" yes="确定" v-on:confirm="deleteFile"></ConfirmDialog>
          </span>
          <FileList v-bind:files="files" v-on:file-click="selectFile($event)" v-on:enter="enterDir($event)" v-on:filing="filing($event)" v-bind:isCurrentPathRoot="isCurrentPathRoot"></FileList>
          <PageList v-bind:total="totalFileNum" v-bind:current="queryParam.pageNum" v-bind:pageSize="queryParam.pageSize" style="margin-top: 40px;" v-on:page-change="changePage($event)"></PageList>
    </div>
  </div>

</template>

<script>
  import http from '../utils/http.js'
  import common from '../utils/common.js'
  import Nav from './Nav'
  import PageList from './PageList'
  import FileList from './FileList'
  import ConfirmDialog from './ConfirmDialog'
  export default {
    name: 'FileManage',
    components: {
      Nav,
      PageList,
      FileList,
      ConfirmDialog,
    },
    methods: {
      /**
       * 更新参数，如果给的空值会设置为默认值
       * */
      updateQueryParam(dirPath, type, pageNum, pageSize) {
        this.queryParam.dirPath = dirPath ? dirPath : '';
        this.queryParam.type = type ? type : this.defaultFileType;
        this.queryParam.pageNum = pageNum && pageNum > 0 ? parseInt(pageNum) : 1;
        this.queryParam.pageSize = pageSize && pageSize > 0 ? parseInt(pageSize) : this.defaultPageSize;
      },
      /**
       * 请求文件列表数据
       * */
      initFileList(queryParam, successCallback, errorCallback) {
        queryParam = queryParam ? queryParam : this.queryParam;
        // 发送请求
        let that = this;
        let callback = (data) => {
          data.list.forEach(file => {
            that.fillData(file);
          });
          that.files = data.list;
          that.totalFileNum = data.total;
          if (successCallback) successCallback();
        }
        http.post('/file', queryParam, callback, errorCallback);
      },
      /**
       * 填充当前文件列表文件信息数据
       * */
      fillData(file) {
        file.filename = common.extractFilename(file.filePath);
        file.selected = false;
        file.iconUrl = IMAGE_URL + file.iconCode;
      },
      /**
       * 加载路由参数初始化文件列表
       * */
      init() {
        this.updateQueryParam(this.$route.params.dirPath, this.$route.params.type, this.$route.params.pageNum, this.$route.params.pageSize);
        this.selectedFile = new Set();
        this.updateSelectedFileStatus();
        this.initFileList();
      },
      /**
       * 切换到上级目录，页码设置为1，类型为默认类型
       * pathIndex: 切换的目标路径在路径数组中的下标
       */
      changeDir(pathIndex) {
        // 触发更新文件列表事件
        let dirPath = '';
        for (let i = 1; i <= pathIndex; i++) {
          if (dirPath) {
            dirPath += PATH_SEP;
          }
          dirPath += this.dirPathList[i];
        }
        this.updateQueryParam(dirPath ? dirPath + PATH_SEP : dirPath, this.defaultFileType, 1, this.queryParam.pageSize);
        this.initFileList();
      },
      /**
       * 进入目录，页码设置为1，类型为默认类型
       * dirname: 目录名称
       * */
      enterDir(dirname) {
        let dirPath = this.queryParam.dirPath + (!this.queryParam.dirPath || this.queryParam.dirPath.endsWith(PATH_SEP) ? dirname : PATH_SEP + dirname) + PATH_SEP;
        let queryParam = common.shallowCopyObj(this.queryParam);
        queryParam.dirPath = dirPath;
        this.initFileList(queryParam, () => this.updateQueryParam(dirPath, this.defaultFileType, 1, this.queryParam.pageSize), (data) => alert(data.errorMsg));
      },
      /**
       * 切换选择过滤的文件类型，页码设置为1
       * */
      changeFileType() {
        this.updateQueryParam(this.queryParam.dirPath, this.queryParam.type, 1, this.queryParam.pageSize);
        this.initFileList();
      },

      /**
       * 选中文件
       * */
      selectFile(fileIndex) {
        if (this.isCurrentPathRoot) {
          // 根目录文件不能选中
          return;
        }
        this.files[fileIndex].selected = !this.files[fileIndex].selected;
        if (this.files[fileIndex].selected) {
          this.selectedFile.add(fileIndex);
        } else {
          this.selectedFile.delete(fileIndex);
        }
        this.updateSelectedFileStatus();
      },
      /**
       * 把被选中的文件路径用,拼接起来
       * */
      updateSelectedFileStatus() {
        this.anyFileSelected = this.selectedFile.size != 0;
        this.selectedFileDescription = this.selectedFilePath().join(", ");
      },
      selectedFilePath() {
        let selectedFilePath = [];
        for (let fileIndex of this.selectedFile.values()) {
          selectedFilePath.push(this.files[fileIndex].filePath);
        }
        return selectedFilePath;
      },
      selectedNotEmptyDir() {
        let selectedFilePath = [];
        for (let fileIndex of this.selectedFile.values()) {
          let file = this.files[fileIndex];
          if (file.type == 'DIR' && !file.empty) {
            selectedFilePath.push(file.filePath);
          }
        }
        return selectedFilePath;
      },
      /**
       * 切换页码
       * */
      changePage(pageNum) {
        this.updateQueryParam(this.queryParam.dirPath, this.queryParam.type, pageNum, this.queryParam.pageSize);
        this.initFileList();
      },
      /**
       * 整理文件：跳转整理页
       * */
      filing(index) {
        let queryParam = Object.assign({}, this.queryParam);
        queryParam['index'] = index;
        this.$router.push({
            name: 'FileFiling',
            params: queryParam
        })
      },
      /**
       * 删除文件
       * */
      deleteFile() {
        let deleteNotEmptyDirAlert = this.selectedNotEmptyDir().join(',');
        if (deleteNotEmptyDirAlert && !confirm('是否删除以下非空目录：' + deleteNotEmptyDirAlert)) {
          return;
        }
        let that = this;
        http.delete_request('/file', this.selectedFilePath(),
            data => {
              that.initFileList();
            }
        );
      },
    },
    computed: {
      dirPathList() {
        return this.defaultLocation.concat(this.queryParam.dirPath ? this.queryParam.dirPath.split(PATH_SEP) : []);
      },
      isCurrentPathRoot() {
        return this.queryParam.dirPath == '';
      }
    },
    watch: {
      '$route' (to, from) {
        this.init();
      }
    },
    data() {
      return {
        queryParam: {
          dirPath: '',
          type: 'ALL',
          pageNum: 1,
          pageSize: 15
        },
        defaultFileType: 'ALL',
        defaultPageSize: 15,
        defaultLocation: ['Root'],
        files: [],
        selectedFile: new Set(),
        selectedFileDescription: '',
        anyFileSelected: false,
        totalFileNum: 0,
      }
    },
    mounted() {
      this.init();
    }
  }
</script>

<style>
  .content {
      width: 90%;
      margin: 20px auto;
  }
  .disabled-link {
    pointer-events: none;
  }

</style>
